/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: LoginPresenter.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.presenter;

import android.app.AlertDialog;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.widget.TextView;

import java.util.regex.Pattern;

import io.bhex.app.BuildConfig;
import io.bhex.app.R;
import io.bhex.app.base.AppUI;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.NetWorkStatus;
import io.bhex.app.view.InputView;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BasePresenter;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.exception.NetException;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.UISafeKeeper;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.account.AccountInfoApi;
import io.bhex.sdk.account.LoginApi;
import io.bhex.sdk.account.bean.BindBean;
import io.bhex.sdk.account.bean.LoginRequestBean;
import io.bhex.sdk.account.bean.LoginVerifyRequest;
import io.bhex.sdk.account.bean.QuickAuthCreateResponse;
import io.bhex.sdk.account.bean.UserInfoBean;
import io.bhex.sdk.data_manager.MMKVManager;
import io.bhex.sdk.security.bean.OrderIdParamResponse;


public class LoginPresenter extends BasePresenter<LoginPresenter.LoginUI> {
    // 手机号码正则表达式
    private Pattern phonePattern = Pattern.compile("1[0-9]{10}");
    private OrderIdParamResponse quickLoginVerifyOrderId;

    @Override
    public void onUIReady(BaseCoreActivity activity, LoginUI ui) {
        super.onUIReady(activity, ui);
    }


    public boolean checkInputContentLegality(boolean DEFULAT_EMAIL, String mobileCode, InputView accountV, InputView pwdV) {
        final String account = accountV.getInputString();
        if (TextUtils.isEmpty(account)) {
//            if (DEFULAT_EMAIL) {
//                accountV.setError(getResources().getString(R.string.input_email));
//            }else{
//                accountV.setError(getResources().getString(R.string.input_phone_number));
//            }
            accountV.setError(getResources().getString(R.string.string_hint_input_mobile_or_email));
            return false;
        }else{
            accountV.setError("");
        }

        if (DEFULAT_EMAIL) {
            //邮箱校验
//            if (!RegexUtils.checkEmail(account)) {
//                accountV.setError(getResources().getString(R.string.input_right_mobile_please));
//                return;
//            }
        }else{
            //手机号校验
//            if (mobileCode.equals("+86")){
//                //判断是中国才校验手机号码，其他国家暂不校验
//                if (!RegexUtils.checkMobile(account)) {
//                    accountV.setError(getResources().getString(R.string.input_right_mobile_please));
//                    return false;
//                }
//            }
        }
        accountV.setError("");

        String pwd = pwdV.getInputString();
        if (TextUtils.isEmpty(pwd)) {
            pwdV.setError(getResources().getString(R.string.input_pwd));
            return false;
        }else{
            pwdV.setError("");
        }

        return true;
    }

    public boolean checkQuickLoginInputContentLegality(boolean DEFULAT_EMAIL, String mobileCode, InputView accountV, InputView verifyCodeInput) {
        final String account = accountV.getInputString();
        if (TextUtils.isEmpty(account)) {
//            if (DEFULAT_EMAIL) {
//                accountV.setError(getResources().getString(R.string.input_email));
//            }else{
//                accountV.setError(getResources().getString(R.string.input_phone_number));
//            }
            accountV.setError(getResources().getString(R.string.input_phone_number));
            return false;
        }else{
            accountV.setError("");
        }

        if (DEFULAT_EMAIL) {
            //邮箱校验
//            if (!RegexUtils.checkEmail(account)) {
//                accountV.setError(getResources().getString(R.string.input_right_mobile_please));
//                return;
//            }
        }else{
            //手机号校验
//            if (mobileCode.equals("+86")){
//                //判断是中国才校验手机号码，其他国家暂不校验
//                if (!RegexUtils.checkMobile(account)) {
//                    accountV.setError(getResources().getString(R.string.input_right_mobile_please));
//                    return false;
//                }
//            }
        }
        accountV.setError("");

        String verifyCode = verifyCodeInput.getInputString();
        if (TextUtils.isEmpty(verifyCode)) {
            verifyCodeInput.setError(getResources().getString(R.string.input_verify));
            return false;
        }else{
            verifyCodeInput.setError("");
        }

        return true;
    }


    /**
     * 登录
     * @param DEFULAT_EMAIL
     * @param mobileCode
     * @param accountV
     * @param pwdV
     * @param userResponseToken
     */
    public void loginVerify(final boolean DEFULAT_EMAIL, String mobileCode, InputView accountV, InputView pwdV, String userResponseToken) {
        if (!NetWorkStatus.isConnected(getActivity())) {
            ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
            return;
        }

        if (!checkInputContentLegality(DEFULAT_EMAIL,mobileCode,accountV,pwdV)) {
           return;
        }

        final String account = accountV.getInputString();
        String pwd = pwdV.getInputString();

        boolean bNet = NetWorkStatus.isConnected(getActivity());
        if (!bNet) {
            ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
            return;
        }

        getUI().hideKeyboard();

        LoginVerifyRequest requestBean = new LoginVerifyRequest();
        requestBean.bEmail = DEFULAT_EMAIL;
        requestBean.account = account;
        requestBean.pwd = pwd;
        requestBean.captcha_response = userResponseToken;
        requestBean.captcha_id = BuildConfig.DEEPKNOW_ID;

        if (DEFULAT_EMAIL) {
        }else{
            requestBean.mobileCode = mobileCode;
        }


        LoginApi.RequestLoginVerify(requestBean, new SimpleResponseListener<BindBean>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("",getString(R.string.string_loading_hint_text));
            }

            @Override
            public void onSuccess(BindBean data) {
                super.onSuccess(data);

                if (CodeUtils.isSuccess(data,true)) {
                    if (!data.isBindGA() && !data.isBindEmail() && !data.isBindMobile()) {
                        //如果都没有绑定 则登录完成，获取用户信息即可
                        getUserInfo(DEFULAT_EMAIL,account);

                    }else{
                        //二次验证流程
                        String requestId = data.getRequestId();
                        if (!TextUtils.isEmpty(requestId)) {
                            IntentUtils.goTwoVerify(getActivity(),getUI().getTwoVerifyRequestCode(),"fromlogin",requestId,"2",data.isBindGA(),data.isBindMobile(),data.isBindEmail(),!DEFULAT_EMAIL);
                        }else{
                            ToastUtils.showShort(getActivity(), getString(R.string.string_login_exception_and_retry));
                        }
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
//                if (error instanceof NetException) {
//                    NetException nt = (NetException)error;
//                    ToastUtils.showShort(getActivity(),nt.getCode()+":"+nt.getShowMessage());
//                }else{
//
//                    ToastUtils.showShort(getActivity(),getResources().getString(R.string.server_error));
//                }
            }
        });
    }

    /**
     * 登录
     * @param DEFULAT_EMAIL
     * @param mobileCode
     * @param accountV
     * @param pwdV
     * @param userResponseToken
     */
    public void login(final boolean DEFULAT_EMAIL, String mobileCode, InputView accountV, InputView pwdV, String userResponseToken,String requestId,int authType,String orderId,String verifyCode) {
        if (!NetWorkStatus.isConnected(getActivity())) {
            ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
            return;
        }
        if (!checkInputContentLegality(DEFULAT_EMAIL,mobileCode,accountV,pwdV)) {
           return;
        }

        final String account = accountV.getInputString();
        String pwd = pwdV.getInputString();

        boolean bNet = NetWorkStatus.isConnected(getActivity());
        if (!bNet) {
            ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
            return;
        }

        getUI().hideKeyboard();

        LoginRequestBean bean = new LoginRequestBean();
        bean.requestId = requestId;
        bean.authType = authType;
        bean.orderId = orderId;
        bean.verifyCode = verifyCode;
//        if (DEFULAT_EMAIL) {
//            params = BParamsBuilder.post()
//                    .url(Urls.API_LOGIN_EAMIL_URL)
//                    .addParam(Fields.FIELD_EAMIL, account)
//                    .addParam(Fields.FIELD_PASSWORD, MD5Utils.encode(pwd))
//                    .addParam("captcha_response", userResponseToken)
//        .addParam("captcha_id", BuildConfig.DEEPKNOW_ID)
//                    .addParam("request_id", requestId)
//                    .addParam("auth_type", authType)
//                    .addParam("order_id", orderId)//手机或者邮箱的二次验证请求返回的orderId  GA方式的验证不填
//                    .addParam("verify_code", verifyCode)
//                    .build();
//        }else{
//            params = BParamsBuilder.post()
//                    .url(Urls.API_LOGIN_MOBILE_URL)
//                    .addParam(Fields.FIELD_MOILE, account)
//                    .addParam(Fields.FIELD_PASSWORD, MD5Utils.encode(pwd))
//                    .addParam(Fields.FIELD_COUNTRY_CODE, mobileCode)
//                    .addParam("captcha_response", userResponseToken)
//        .addParam("captcha_id", BuildConfig.DEEPKNOW_ID)
//                    .addParam("request_id", requestId)
//                    .addParam("auth_type", authType)
//                    .addParam("order_id", orderId)//手机或者邮箱的二次验证请求返回的orderId  GA方式的验证不填
//                    .addParam("verify_code", verifyCode)
//                    .build();
//        }

        LoginApi.RequestLogin(bean, UISafeKeeper.guard(getUI(), new SimpleResponseListener<UserInfoBean>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("",getResources().getString(R.string.string_loading_hint_text));
            }

            @Override
            public void onSuccess(UserInfoBean data) {
                super.onSuccess(data);
                if (CodeUtils.isSuccess(data,true)) {
                    setLoginSuccess();
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (error instanceof NetException) {
                    NetException nt = (NetException)error;
                    ToastUtils.showShort(getActivity(),nt.getCode()+":"+nt.getShowMessage());
                }else{

                    ToastUtils.showShort(getActivity(),getResources().getString(R.string.server_error));
                }
            }
        }));
    }

    /**
     * 设置 确认登录成功
     */
    private void setLoginSuccess() {
        // 登录成功
        ToastUtils.showShort(getActivity(), getResources().getString(R.string.string_login_success));
        //保存一下用户的账号
        boolean fingerOpen = SPEx.isFingerOpen();
        if (fingerOpen){
            SPEx.setFingerAuth(true);
            AppData.HOME_LOCKED=false;
            AppData.isHome=false;
        }

        getUI().loginSuccess();
    }


    /**
     * 获取用户信息
     * @param DEFULAT_EMAIL
     * @param account
     */
    public void getUserInfo(final boolean DEFULAT_EMAIL, final String account){
        LoginApi.GetUserInfo(DEFULAT_EMAIL, account, new SimpleResponseListener<UserInfoBean>(){
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(UserInfoBean data) {
                super.onSuccess(data);
                if (CodeUtils.isSuccess(data,true)) {
                    ToastUtils.showShort(getActivity(), getResources().getString(R.string.string_login_success));
                    //保存一下用户的账号
                    boolean fingerOpen = SPEx.isFingerOpen();
                    if (fingerOpen){
                        SPEx.setFingerAuth(true);
                        AppData.HOME_LOCKED=false;
                        AppData.isHome=false;
                    }

                    getUI().loginSuccess();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 切换登录方式
     * @param defulat_email
     */
    public void switchSignupWay(boolean defulat_email) {

    }

    /**
     * 快速登录
     * @param mobileCodeTv
     * @param mobile
     * @param verifyCode
     */
    public void requestQuickLogin(TextView mobileCodeTv, String mobile, String verifyCode) {
        String mobileCode = mobileCodeTv.getText().toString().replace("+","");
        if (quickLoginVerifyOrderId == null) {
            ToastUtils.showShort(getActivity().getResources().getString(R.string.string_verify_code_invalid));
            return;
        }
        String orderId = quickLoginVerifyOrderId.getOrderId();
        if (TextUtils.isEmpty(orderId)) {
            ToastUtils.showShort(getActivity().getResources().getString(R.string.string_verify_code_invalid));
            return;
        }
        LoginApi.requestQuickAuthCreate("mobile",mobileCode,mobile,verifyCode,orderId,new SimpleResponseListener<QuickAuthCreateResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(QuickAuthCreateResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    if (response.isNeedCheckPassword()) {
                        getUI().needPasswdAndGoVerifyPasswd(response.getRequestId());
                    }else{
                        setLoginSuccess();
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (error instanceof NetException) {
                    NetException nt = (NetException)error;
                    ToastUtils.showShort(getActivity(),nt.getCode()+":"+nt.getShowMessage());
                }else{

                    ToastUtils.showShort(getActivity(),getResources().getString(R.string.server_error));
                }
            }
        });

    }

    /**
     * 快速登录-二次确认密码
     * @param dialog
     * @param requestId
     * @param passwd
     */
    public void requestQuickLoginComfirm(final AlertDialog dialog, String requestId, String passwd) {
        LoginApi.requestQuickAuthComfirm(requestId,passwd,new SimpleResponseListener<UserInfoBean>(){
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(UserInfoBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    if (dialog != null) {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                    setLoginSuccess();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (error instanceof NetException) {
                    NetException nt = (NetException)error;
                    ToastUtils.showShort(getActivity(),nt.getCode()+":"+nt.getShowMessage());
                }else{

                    ToastUtils.showShort(getActivity(),getResources().getString(R.string.server_error));
                }
            }
        });

    }

    /**
     * 快速登录-获取验证码
     * @param mobileCodeTv
     * @param accountEdit
     * @param token
     */
    public void quickLoginVerify(TextView mobileCodeTv, InputView accountEdit, String token) {
        String mobileCode = mobileCodeTv.getText().toString().replace("+","");
        String mobile = accountEdit.getInputString();
        if (TextUtils.isEmpty(mobile)) {
            ToastUtils.showShort(getActivity(), getResources().getString(R.string.input_phone_number));
            return;
        } else {
            AccountInfoApi.requestMobileVerifyCodeOfQuickLogin(mobile,token,BuildConfig.DEEPKNOW_ID,mobileCode,new SimpleResponseListener<OrderIdParamResponse>(){
                @Override
                public void onBefore() {
                    super.onBefore();
                    getUI().showProgressDialog("","");
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    getUI().dismissProgressDialog();
                }

                @Override
                public void onSuccess(OrderIdParamResponse response) {
                    super.onSuccess(response);
                    if (CodeUtils.isSuccess(response,true)) {
                        quickLoginVerifyOrderId = response;

                        getUI().setAuthTvStatus(false);
                        timer.start();
                    }
                }

                @Override
                public void onError(Throwable error) {
                    super.onError(error);
                }
            });
        }

    }

    /**
     * 倒计时
     */
    private CountDownTimer timer = new CountDownTimer(AppData.DOWN_TIME_CODE, AppData.DOWN_TIME_INTERVAL_CODE) {
        @Override
        public void onTick(long millisUntilFinished) {
            getUI().setAuthTv((millisUntilFinished / 1000)
                    + getActivity().getResources().getString(
                    R.string.after_second));
        }

        @Override
        public void onFinish() {
            getUI().setAuthTvStatus(true);
            getUI().setAuthTv(getResources().getString(
                    R.string.string_get_auth_code));
        }
    };

    /**
     * 是否快速登录
     * @param isFastLogin
     */
    public void setLoginAccount(boolean isFastLogin, InputView accountEdit){
        String account = "";
        if(isFastLogin){
            account = MMKVManager.getInstance().mmkv().decodeString("bhex_phone","");
        }else{
            account = MMKVManager.getInstance().mmkv().decodeString("bhex_email","");
        }

        if(!TextUtils.isEmpty(account)){
            accountEdit.setInputString(account);
        }
    }

    /**
     * 保存登录使用的账号
     * @param isFastLogin
     * @param account
     */
    public void saveLoginAccount(boolean isFastLogin, String account){
        if(TextUtils.isEmpty(account)){
            return;
        }
        if(isFastLogin){
            MMKVManager.getInstance().mmkv().encode("bhex_phone",account);
        }else {
            MMKVManager.getInstance().mmkv().encode("bhex_email",account);

        }
    }

    public interface LoginUI extends AppUI {
        void loginSuccess();

        void loginFailed(String reason);

        void hideKeyboard();

        void setAccount(String accountName);

        String getMobileCode();

        int getTwoVerifyRequestCode();

        void needPasswdAndGoVerifyPasswd(String requestId);

        void setAuthTvStatus(boolean b);

        void setAuthTv(String s);
    }
}
